package com.supermarket.service;

import com.supermarket.entity.Cart;
import com.supermarket.mapper.CartMapper;
import com.supermarket.common.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 购物车服务实现类
 */
@Service
public class CartService {

    @Autowired
    private CartMapper cartMapper;
    
    @Autowired
    private RedisUtil redisUtil;
    
    // Redis缓存相关的Key前缀
    private static final String CART_KEY_PREFIX = "cart:user:";
    private static final int CART_CACHE_SECONDS = 604800; // 购物车缓存默认7天

    /**
     * 获取用户购物车列表
     * 先从Redis缓存获取，未命中再从数据库查询
     */
    public List<Cart> getCartListByUserId(Integer userId) {
        String cartKey = CART_KEY_PREFIX + userId;
        
        // 尝试从缓存获取
        Object cached = redisUtil.get(cartKey);
        if (cached != null) {
            return (List<Cart>) cached;
        }
        
        // 缓存未命中，查询数据库
        List<Cart> cartList = cartMapper.selectByUserId(userId);
        
        // 将结果存入缓存
        if (cartList != null && !cartList.isEmpty()) {
            redisUtil.set(cartKey, cartList, CART_CACHE_SECONDS);
        }
        
        return cartList;
    }

    /**
     * 添加商品到购物车
     * 同时更新数据库和缓存
     */
    @Transactional
    public int addCart(Cart cart) {
        int result;
        
        // 查询是否已存在该商品
        Cart existCart = cartMapper.selectByUserIdAndCommodityId(cart.getUserId(), cart.getCommodityId());
        if (existCart != null) {
            // 已存在，增加数量
            existCart.setQuantity(existCart.getQuantity() + cart.getQuantity());
            result = cartMapper.update(existCart);
        } else {
            // 不存在，新增记录
            result = cartMapper.insert(cart);
        }
        
        // 清除购物车缓存，确保数据一致性
        clearCartCache(cart.getUserId());
        
        return result;
    }

    /**
     * 更新购物车商品数量
     */
    public int updateQuantity(Integer id, Integer quantity) {
        Cart cart = cartMapper.selectById(id);
        int result;
        
        if (quantity <= 0) {
            // 数量小于等于0，直接删除
            result = cartMapper.deleteById(id);
        } else {
            result = cartMapper.updateQuantity(id, quantity);
        }
        
        // 更新缓存
        if (cart != null) {
            clearCartCache(cart.getUserId());
        }
        
        return result;
    }

    /**
     * 更新购物车商品选中状态
     */
    public int updateSelected(Integer id, Boolean selected) {
        Cart cart = cartMapper.selectById(id);
        int result = cartMapper.updateSelected(id, selected);
        
        // 更新缓存
        if (cart != null) {
            clearCartCache(cart.getUserId());
        }
        
        return result;
    }

    /**
     * 批量更新购物车商品选中状态
     */
    public int updateSelectedBatch(Integer userId, Boolean selected) {
        int result = cartMapper.updateSelectedBatch(userId, selected);
        
        // 更新缓存
        clearCartCache(userId);
        
        return result;
    }

    /**
     * 删除购物车商品
     */
    public int deleteCart(Integer id) {
        Cart cart = cartMapper.selectById(id);
        int result = cartMapper.deleteById(id);
        
        // 更新缓存
        if (cart != null) {
            clearCartCache(cart.getUserId());
        }
        
        return result;
    }

    /**
     * 批量删除购物车商品
     */
    public int deleteCartBatch(List<Integer> ids) {
        // 获取这些购物车项所属的用户ID列表
        List<Integer> userIds = new ArrayList<>();
        for (Integer id : ids) {
            Cart cart = cartMapper.selectById(id);
            if (cart != null && !userIds.contains(cart.getUserId())) {
                userIds.add(cart.getUserId());
            }
        }
        
        int result = cartMapper.deleteBatch(ids);
        
        // 更新缓存
        for (Integer userId : userIds) {
            clearCartCache(userId);
        }
        
        return result;
    }

    /**
     * 清空用户购物车
     */
    public int clearCart(Integer userId) {
        int result = cartMapper.deleteByUserId(userId);
        
        // 清除缓存
        clearCartCache(userId);
        
        return result;
    }
    
    /**
     * 清除用户购物车缓存
     */
    private void clearCartCache(Integer userId) {
        String cartKey = CART_KEY_PREFIX + userId;
        redisUtil.delete(cartKey);
    }
} 